package com.nartosoft.tubuloader;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

/**
 * @author eb
 * 
 * Writes upload results and error messages to a logfile.
 */
public class LogfileWriter implements EventListener {
	private final boolean logImageFiles;

	private final boolean logUrls;

	private final boolean logErrors;

	private final Writer logFile;

	public LogfileWriter(String logfileName, boolean logImageFiles,
			boolean logUrls, boolean logErrors) throws IOException {
		this.logImageFiles = logImageFiles;
		this.logUrls = logUrls;
		this.logErrors = logErrors;
		File f = new File(logfileName);
		if (!f.exists()) {
			f.createNewFile();
		}
		logFile = new FileWriter(f, true);
	}

	public void onUpload(String fileName, String url) {
		if (logImageFiles) {
			writeToLogfile(fileName);
		}
		if (logUrls) {
			writeToLogfile(url);
		}
		if (logImageFiles || logUrls) {
			writeToLogfile(""); // separate entries with an empty line
		}
	}

	public void onError(String message) {
		if (logErrors) {
			writeToLogfile("ERROR: " + message);
		}
	}

	private void writeToLogfile(String message) {
		try {
			logFile.write(message + "\n");
		}
		catch (IOException exc) {
			exc.printStackTrace();
		}
	}

	/**
	 * Closes logfile.
	 */
	public void onAllFilesDone() {
		try {
			logFile.close();
		}
		catch (IOException exc) {
			exc.printStackTrace();
		}
	}
}
